import 'package:flutter/material.dart';
import 'package:flutter_wan_android/core/widget/custom_app_bar.dart';
import 'package:flutter_wan_android/feature/user/register_view_model.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';

import '../../core/widget/loading_dialog.dart';
import '../core/ui_state.dart';
import 'user_text_field.dart';

class RegisterScreen extends StatefulWidget {


  const RegisterScreen({super.key});

  @override
  State<RegisterScreen> createState() => _RegisterScreenState();
}

class _RegisterScreenState extends State<RegisterScreen> {
  final TextEditingController _usernameController = TextEditingController();

  final TextEditingController _passwordController = TextEditingController();

  final TextEditingController _rePasswordController = TextEditingController();

  late final RegisterViewModel _viewModel;

  @override
  void initState() {
    super.initState();
    _viewModel = context.read<RegisterViewModel>();
    _viewModel.addListener(_uiStateChange);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar(
        title: "注册",
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            SizedBox(height: 40),
            UserTextField(hintText: "请输入账号", controller: _usernameController),
            SizedBox(height: 20),
            UserTextField(hintText: "请输入密码", controller: _passwordController,obscureText: true,),
            SizedBox(height: 20),
            UserTextField(hintText: "请输入再次输入密码", controller: _rePasswordController,obscureText: true,),
            SizedBox(height: 80),
            _buildRegisterButton(context),
          ],
        ),
      ),
    );
  }

  SizedBox _buildRegisterButton(BuildContext context) {
    return SizedBox(
      width: 200,
      child: ElevatedButton(
        onPressed: _register,
        style: ButtonStyle(
          backgroundColor: WidgetStatePropertyAll(
            Theme.of(context).primaryColor,
          ),
        ),
        child: Text("注册", style: TextStyle(color: Colors.white, fontSize: 16)),
      ),
    );
  }

  void _register(){
    _viewModel.register(_usernameController.text, _passwordController.text, _rePasswordController.text);
  }

  void _uiStateChange() {
    final uiState = _viewModel.uiState;
    if (uiState is! Loading) {
      LoadingDialog.hide(context);
    }
    switch (uiState) {
      case Loading():
        LoadingDialog.show(context);
      case Success():
        Fluttertoast.showToast(msg: "注册成功");
        Navigator.pop(context);
      case Error():
        Fluttertoast.showToast(msg: _viewModel.message);
    }
  }

  @override
  void dispose() {
    _usernameController.dispose();
    _passwordController.dispose();
    _rePasswordController.dispose();
    _viewModel.removeListener(_uiStateChange);
    super.dispose();
  }
}
